<?php

declare(strict_types=1);

namespace App\Service;

use App\Library\Common;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpMessage\Server\Request;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Snowflake\IdGeneratorInterface;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * 商家保证金订单服务
 * Class FlyShopCashOrderService
 * @package App\Service
 */
class FlyShopCashOrderService extends BaseService
{

    /**
     * @Inject
     * @var RequestInterface
     */
    private $request;

    /**
     * @Inject
     * @var FlyShopService
     */
    private $flyShop;

    /**
     * 创建保证金订单
     * @param int $user_id
     * @return array
     */
    public function createCashOrder(int $user_id): array
    {
        $return = [
            'msg' => "",
            'res' => true,
            'cash_order_sn' => ""
        ];

        $my_shop = $this->flyShop->getMyShop($user_id);
        // 获取已缴纳保证金金额
        if (empty($my_shop) || $my_shop['type'] == 3) {
            $return['msg'] = "店铺不存在";
            $return['res'] = false;
            return $return;
        }
        // 已缴纳金额
        $has_paid = (float)$my_shop['paid_cash'];
        // 获取店铺行业保证金列表
        $industries = $my_shop['with_industry'];
        $shop_cert_type = $my_shop['type'];
        // 按店铺类型排序保证金
        $re = usort($industries, function ($k1, $k2) use ($shop_cert_type) {
            if ($shop_cert_type == 1) {// 个人
                if ($k1['with_industry_cash']['individual_price'] == $k2['with_industry_cash']['individual_price']) {
                    return 0;
                }
                return ($k1['with_industry_cash']['individual_price'] < $k2['with_industry_cash']['individual_price']) ? 1 : -1;
            } elseif ($shop_cert_type == 2) {// 个体工商户
                if ($k1['with_industry_cash']['individual_business_price'] == $k2['with_industry_cash']['individual_business_price']) {
                    return 0;
                }
                return ($k1['with_industry_cash']['individual_business_price'] < $k2['with_industry_cash']['individual_business_price']) ? 1 : -1;
            } else { // 企业
                if ($k1['with_industry_cash']['enterprise_price'] == $k2['with_industry_cash']['enterprise_price']) {
                    return 0;
                }
                return ($k1['with_industry_cash']['enterprise_price'] < $k2['with_industry_cash']['enterprise_price']) ? 1 : -1;
            }
        });
        if (!$re) {
            $return['res'] = false;
            $return['msg'] = "未获取到保证金金额";
            return $return;
        }
        // 获取保证金行业
        $cost_industry = $industries[0];
        if ($shop_cert_type == 1) {
            $cost_price = $cost_industry['with_industry_cash']['individual_price'];
            $cost_industry_id = $cost_industry['with_industry_cash']['id'];
        } elseif ($shop_cert_type == 2) {
            $cost_price = $cost_industry['with_industry_cash']['individual_business_price'];
            $cost_industry_id = $cost_industry['with_industry_cash']['id'];
        } else {
            $cost_price = $cost_industry['with_industry_cash']['enterprise_price'];
            $cost_industry_id = $cost_industry['with_industry_cash']['id'];
        }
        $cost_price = Common::yuan2fen($cost_price);
        $now_cost_price = Common::yuan2fen($has_paid);
        if ($now_cost_price >= $cost_price) {
            // 不需要缴纳保证金
            $return['res'] = false;
            $return['msg'] = "当前不需要缴纳保证金";
            return $return;
        }
        // 应缴纳金额
        $should_pay = $now_cost_price - $cost_price;
        try {
            $cash_order = [
                'cash_sn' => $this->generateSn(),
                'type' => $cost_price == 0 ? 1 : 2,
                'shop_id' => $my_shop['id'],
                'user_id' => $user_id,
                'pay_price' => Common::fen2yuan($should_pay),
                'create_time' => time(),
                'cash_price' => $cost_price,
                'industry_id' => $cost_industry_id,
                'industry_name' => $cost_industry['industry_name']
            ];
            $id = $this->getModelInstance()->insertGetId($cash_order);
            if (!$id) {
                $return['msg'] = "创建订单失败";
                $return['res'] = false;
                return $return;
            }
        } catch (NotFoundExceptionInterface $e) {
            $return['msg'] = "创建失败1";
            $return['res'] = false;
            return $return;
        } catch (ContainerExceptionInterface $e) {
            $return['msg'] = "创建失败2";
            $return['res'] = false;
            return $return;
        } catch (\Throwable $e) {
            $return['msg'] = "创建失败3";
            $return['res'] = false;
            return $return;
        }
        $return['cash_order_sn'] = $cash_order['cash_sn'];
        return $return;
    }


    /**
     * 查询商家保证金订单
     * @param string $order_sn
     * @return array
     */
    public function getCashOrderBySn(string $order_sn): array
    {
        $pay_order = $this->getModelInstance()
            ->where(['cash_sn' => $order_sn, 'paid_price' => 0])
            ->first();
        if (empty($pay_order)) {
            return [];
        }
        return $pay_order->toArray();
    }

    /**
     * 支付成功回调更新订单状态
     * @param string $order_sn
     * @param string $pay_type
     * @param string $pay_method
     * @param string $pay_outer_sn
     * @return bool
     */
    public function cashNotifyPay(string $order_sn, string $pay_type, string $pay_method, string $pay_outer_sn)
    {
        // 获取订单实例
        $instance = $this->getModelInstance()->where('order_sn', '=', $order_sn)->first();
        if (empty($intance)) {
            return false;
        }
        $instance->is_pay = 1;
        $instance->pay_time = time();
        $instance->pay_type = $pay_type;
        $instance->pay_method = $pay_method;
        $instance->paid_price = Db::raw('pay_price');
        $instance->pay_outer_sn = $pay_outer_sn;
        if (!$instance->save()) {
            return false;
        }
        // 更新店铺保证金信息
        return $this->flyShop->updateShopCash($instance->shop_id, $instance->industry_id, $instance->cash_price);
    }

    /**
     * 生成唯一单号
     * @param string $prefix
     * @return string
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function generateSn($prefix = 'CO')
    {
        usleep(300);
        $container = ApplicationContext::getContainer();
        $generator = $container->get(IdGeneratorInterface::class);
        $id = $generator->generate();
        return $prefix . date('Ym') . substr(strval($id), 8) . rand(100000, 999999);
    }
}